const app = getApp()
const globalData = app.globalData
const utils = require('../../../utils/util')
const api = require('../../../api/index')
const pay = require('../../../utils/pay')
const http = require('../../../utils/http')
const {
    object,
    unique
} = require('../../../utils/underscore')

Page({
    data: {
        ShippingAmount: null,
        itemSpecName: "",
        iteams: "",
        kanjiaType: 0, //  0是自己砍一刀   1是叫朋友帮忙砍一刀
        iteamSum: 0,
        CouponName: "选择优惠券",
        CouponId: "",
        iteamArr: [],
        sumText: "",
        sums: "0",
        from: 0, //  // 1 来自详情页面 0 来自购物车 2 补货 3 自提
        source: '', // 商品类型
        activityId: '', // 活动id,附加在商品的活动id,普通商品没有活动id
        showBuyData: {},
        isIpx: globalData.isIpx,
        checked: false,
        showCoupon: false,
        couponList: [],
        // couponCut: 0, // 优惠券减免
        addressList: [],
        addressListIndex: 0,
        docId: '', // 皮肤管理师编号
        remark: '', // 买家留言
        filter: {
            userAddressId: "",
            userCouponId: "",
            remarks: "",
            orderDetails: [{
                goodsId: "",
                num: 0,
                goodsSSpecId: "",
                // orderDoctorRequests: [
                //     {
                //         doctorId: ""
                //     }
                // ]
            }],
            orderType: 0, // 1 人气 2 黑标 3 门槛
            appointmentTime: "",
            deliveryTime: "",
            invitationId: '',
            doctorUserId: ''
        },
        filter2: {
            userAddressId: "",
            userCouponId: "",
            remarks: "",
            goodsSeckillId: "",
            goodsSSpecId: "",
            num: 0,
            orderType: 0,
            appointmentTime: "",
            deliveryTime: "",
            invitationId: "",
            doctorUserId: ""
        },
        filter3: {
            orderSpellId: "", // 拼团id，有就是加入拼团，没有就是发起拼团
            goodsId: "",
            goodsSSpecId: "",
            userAddressId: "",
            userCouponId: "",
            remarks: "",
            num: 1,
            orderType: 0,
            appointmentTime: "",
            deliveryTime: "",
            invitationId: "",
            doctorUserId: ""
        },

        toast: {
            visible: false,
            text: ''
        },
        status: 0,
        imageBaseUri: globalData.imageBaseUri,
        discount: 0,
        discountList: [],
        agentInfo: {}, // 顾问信息
        moneyBox: null,
        isCarCoupon: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this
        console.log('options', options)

        that.setData({
            activityId: options.activityId,
            iteams: options
        })
        let orderInfo = JSON.parse(decodeURIComponent(options.goods));
        console.log(orderInfo, 1234567)
        if (options.isCar == 1) {
            let money = JSON.parse(decodeURIComponent(options.money))
            money.sum = Number(money.sum);
            // console.log(money)
            that.setData({
                moneyBox: money
            })
        }
        console.log('orderInfo111', orderInfo)
        if (options.from == 0) {
            for (let i = 0; i < orderInfo.length; i++) {
                for (let j = 0; j < orderInfo[i].GoodsPageDto.GoodsSpecDtos.length; j++) {
                    if (orderInfo[i].GoodsSpecId == orderInfo[i].GoodsPageDto.GoodsSpecDtos[j].Id) {
                        orderInfo[i].GoodsSpecName = orderInfo[i].GoodsPageDto.GoodsSpecDtos[j].Name;
                        orderInfo[i].GoodsPageDto.Price = orderInfo[i].GoodsPageDto.GoodsSpecDtos[j].Price;
                    }
                }
            }
        }
        if (options.source != "") {
            that.setData({
                orderTypes: options.source
            })
            console.log(this.data.orderTypes);
        }
        this.setData({
            orderInfo: orderInfo,
            from: options.from || 0,
            source: options.source,
            activityId: options.activityId,
            showBuyData: JSON.parse(options.showBuyData || '{}')
        })
        console.log(this.data.orderInfo);

        this.reload();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this
        this.reload()

    },
    // 拿砍价信息
    getKJ() {
        let that = this
        let {
            Id
        } = wx.getStorageSync('userinfo')
        console.log("活动id", this.data.activityId);
        let obj = {
            user_id: Id,
            id: that.data.activityId
        }
        http.request("POST", "bargain/user_details", obj).then((res) => {
            console.log(res);
        })
    },
    // 参与砍价
    // async takeKJ(){
    //      // 砍价商品
    //         // 0元购
    //         let that=this
    //         console.log(this.data.sum);
    //         if (this.data.sum == 0 ) {
    //             let res = await api.bargain.createBargainOrder({
    //                 id: this.data.activityId,
    //                 spec_id: this.data.orderInfo[0].spec.Id,
    //                 num: this.data.orderInfo[0].count,
    //                 address_id: this.data.addressList[0].Id,
    //                 remark: this.data.remark
    //             });
    //             console.log(res);
    //             if (res.data.ErrCode != 0) {
    //                 that.setData({
    //                     loading: false
    //                 })
    //                 wx.showModal({
    //                     content: res.data.ErrMsg,
    //                 })

    //             } else {
    //                 http.request("POST", "/Pay/bargain_amount_zero", res.data.ResData).then((res) => {
    //                     console.log(res);
    //                     if (res.data.ErrCode != 0) {
    //                         console.error(res.data.ErrMsg)
    //                     } else {
    //                         wx.showToast({
    //                             title: '下单成功',
    //                             icon: 'success',
    //                             duration: 2000
    //                         })

    //                         wx.redirectTo({
    //                             url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter2.goodsSeckillId}&sum=${this.data.sum}&couponcut=${this.data.couponCut}`,
    //                         })

    //                     }
    //                 })
    //             }
    //         } else {
    //             try {
    //                 let res = await api.bargain.createBargainOrder({
    //                     id: this.data.activityId,
    //                     spec_id: this.data.orderInfo[0].spec.Id,
    //                     num: this.data.orderInfo[0].count,
    //                     address_id: this.data.addressList[0].Id,
    //                     remark: this.data.remark
    //                 }).then((ress) => {
    //                     console.log(ress);
    //                     that.setData({
    //                         loading: false
    //                     })
    //                     if (ress.data.ErrCode==0) {
    //                         that.setData({
    //                             sum:that.data.sum-ress.data.ResData.BargainAmount,
    //                             kanjiaType:1
    //                         })
    //                         wx.showModal({
    //                             content: `成功砍下${ress.data.ResData.BargainAmount}元`,
    //                         })

    //                     }else{
    //                         wx.showModal({
    //                             content: ress.data.ErrMsg,
    //                         })
    //                     }

    //                     // wx.redirectTo({
    //                     //     url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter2.goodsSeckillId}&sum=${this.data.sum}&couponcut=${this.data.couponCut}`,
    //                     // })
    //                 })


    //             } catch (e) {

    //                 this.setData({
    //                     loading: false,
    //                     toast: {
    //                         visible: true,
    //                         text: e.data && e.data.ErrMsg
    //                     },
    //                 })
    //             }
    //         }
    // },

    toAddress() {
        wx.navigateTo({
            url: '/pages/product/address/address',
        })
    },

    checkSkin() {
        this.setData({
            checked: !this.data.checked
        })
    },

    reload() {
        if (!utils.getLoginState()) {
            return utils.checkLoginState({
                routeUri: 3,
                uri: `/pages/product/confirm/confirm?goods=${encodeURIComponent(this.data.orderInfo)}&from=${this.data.from}`
            });
        }
        this.getAddress();
        // this.getMyCoupons();
        this.getDiscount();
        // 获取商品可用优惠卷
        this.getDiscounts();
        this.setData({
            agentInfo: wx.getStorageSync('agentInfo') || {}
        })
    },
    getFreight() {
        let that = this
        let id = []
        that.data.orderInfo.forEach(e => {
            console.log(e)
            if (e.spec) {
                id.push({
                    goodsId: e.spec.GoodsId,
                    num: e.count
                })
            } else {
                id.push({
                    goodsId: e.GoodsId,
                    num: e.Num
                })
            }
        })
        console.log(id)
        api.order.freight({
            goodsInfo: id,
            userAddressId: that.data.addressList[that.data.addressListIndex].Id
        }).then(res => {
            console.log(res)
            if (res.data.ErrCode == 0) {
                that.setData({
                    ShippingAmount: res.data.ResData
                })
            } else {
                wx.showToast({
                    title: res.data.ErrMsg,
                    icon: 'none'
                })
            }
        })
    },


    async getDiscounts() {
        let that = this
        try {
            console.log(that.data.orderInfo)

            let obj = null
            if (that.data.orderTypes == 'cart') {
                let arr = []
                that.data.orderInfo.map(e => {
                    console.log(e)
                    arr.push({goods_id: e.GoodsId})
                })
                obj = arr
            } else {
                obj = {
                    goods_id: that.data.orderInfo[0].spec.GoodsId
                }
            }

            console.log(obj, "526626526");
            http.request("POST", "/coupon/UserCouponUse", obj).then((res) => {
                if (res.data.ErrCode == 0) {
                    that.setData({
                        couponList: res.data.ResData
                    })
                    console.log(that.data.couponList);
                } else {
                    console.error(res.data.ResData)
                }
            })
        } catch (e) {
            console.log(e);
        }
    },

    // 获取地址
    async getAddress() {
        let that = this
        try {
            let res = await api.address.getAddressList(),
                data = res.data.ResData || [];

            this.setData({
                addressList: data || [],
                status: 2

            })

            let index = 0
            for (let i = 0; i < this.data.addressList.length; i++) {
                if (this.data.addressList[i].IsDefault == 1) {
                    index = i
                    break
                }
            }
            that.setData({
                addressListIndex: index,
                Addres: JSON.parse(JSON.stringify(data[index].Id))
            })
            // that.data.Addres=JSON.parse(JSON.stringify(data[index].Id))
            wx.setStorageSync('AddressId', this.data.Addres)
            console.log(this.data.Addres);
            console.log(this.data.addressListIndex);
            console.log(res, this.data.addressList, '地址列表')
            this.getFreight()
        } catch (e) {
            console.log(e, '获取地址失败')
        }
    },

    // // 获取当前用户的优惠券列表
    // async getMyCoupons() {
    //     try {
    //         let res = await api.coupon.getMyCoupons(1),
    //             data = res.data.ResData || [];
    //         this.setData({
    //             couponList: data
    //         })

    //         // console.log(data[0].CouponDto.Meet, '满足', this.data.sum, 'sum')

    //         if (data[0] && this.data.sum >= data[0].CouponDto.Meet) {
    //             // 自动选择第一张优惠券
    //             this.chooseCoupon();

    //         }

    //         console.log(res, '我的优惠券列表')
    //     } catch (e) {
    //         console.log(e, '获取我的优惠券列表失败')
    //     }
    // },

    // 显示coupon弹框
    showCoupon() {
        this.setData({
            showCoupon: true
        })
    },

    // 隐藏coupon弹框
    hideCoupon() {
        this.setData({
            showCoupon: false
        })
    },

    // 选择优惠券
    chooseCoupon(e) {
        console.log(e)
        this.setData({
            sum: this.data.iteamSum
        })
        let that = this
        let item = e.currentTarget.dataset.item;
        if (e) {
            // console.log(this.data.sum, item)
            console.log(typeof item.Meet)
            console.log(this.data.sum, item.Meet)
            let sum = null
            if(that.data.orderTypes == 'cart'){
                that.data.orderInfo.map(e => {
                    console.log(e)
                    if(e.GoodsPageDto.IsCoupon == 1){
                        sum += Number(e.Amount) * Number(e.Num)
                    }
                })
            } else {
                sum = this.data.sum
            }
            console.log(sum)
            // if ( Number(this.data.sum) < Number(item.Meet) ) {
            if (Number(sum) < Number(item.Meet)) {
                console.log(123)
                this.setData({
                    toast: {
                        visible: true,
                        text: '未满足使用条件'
                    },

                })
                this.hideCoupon();
                return
            } else {
                this.setData({
                    CouponId: item.Id,
                    CouponName: item.Title,
                    sum: this.data.sum - item.Value,
                    isCarCoupon: true,
                    carCouponSum: sum - item.Value,
                    // moneyBox:{
                    //     'sum':sum - item.Value,
                    // }
                })
                console.log(this.data.CouponId);
                this.hideCoupon();

            }



        } else {
            if (this.data.couponList && this.data.sum < this.data.couponList[0].CouponDto.Meet) {
                console.log(321)
                this.setData({
                    toast: {
                        visible: true,
                        text: '未满足使用条件'
                    }
                })
                return
            }
            this.setData({
                couponCut: this.data.couponList && this.data.couponList.length ? this.data.couponList[0].CouponDto.Value : 0,
                chosenCoupon: this.data.couponList && this.data.couponList.length ? this.data.couponList[0] : {}
            })
        }

    },

    // 买家留言
    inputMsg(e) {
        this.setData({
            remark: e.detail.value
        })
    },

    // 皮肤管理师编号
    inputNumber(e) {
        this.setData({
            docId: e.detail.value
        })
    },

    // 提交订单
    async submit(e) {
        let that = this
        let orderInfo = this.data.orderInfo,
            obj = {},
            arr = [];
        console.log(this.data.addressList, 'addreslist')
        if (!this.data.addressList.length) {
            this.setData({
                toast: {
                    visible: true,
                    text: '请选择收货地址'
                }
            })

            return true
        }

        // 黑标产品必须填写皮肤管理师编号
        // if (orderInfo.length == 1 && (orderInfo[0] && orderInfo[0].type == 2 || orderInfo[0].GoodsPageDto && orderInfo[0].GoodsPageDto.Type == 2)) {
        //     if (!this.data.docId) {
        //         this.setData({
        //             toast: {
        //                 visible: true,
        //                 text: '请填写皮肤管理师编号'
        //             }
        //         })
        //         return
        //     }
        // }

        console.log(this.data.orderInfo, 'orderInfo');
        console.log(this.data.from, "wuyu");

        orderInfo.forEach(item => {
            if (this.data.from == 1 || this.data.from == 2 || this.data.from == 3) { // 1 来自详情页 2 补货 3 自提
                console.log(this.data.isGroup);
                if (this.data.isGroup) {
                    console.log(this.data.CouponId);
                    this.setData({
                        filter3: {
                            orderSpellId: this.data.groupId, // 拼团id，有就是加入拼团，没有就是发起拼团
                            goodsId: item.spec.GoodsId,
                            goodsSSpecId: item.spec.Id,
                            userAddressId: this.data.addressList[0].Id || '',
                            userCouponId: this.data.chosenCoupon && this.data.chosenCoupon.Id || '',
                            // userCouponId:this.data.CouponId,
                            remarks: this.data.remark || '',
                            num: 1,
                            orderType: item.type,
                            appointmentTime: "",
                            deliveryTime: "",
                            invitationId: wx.getStorageSync('inviteId') || '',
                            doctorUserId: this.data.docId,
                            shareID: wx.getStorageSync('shareID')
                        }
                    })
                } else if (item.spec && item.spec.SeckillPric) {

                    this.setData({
                        'filter2.goodsSeckillId': item.spec.seckillId,
                        'filter2.num': item.count,
                        'filter2.goodsSSpecId': item.spec.Id,
                        'filter2.orderType': item.type
                    })
                } else {

                    // 普通商品参数结构不同
                    if (this.data.from == 2) { // 库存补货下单
                        obj = {
                            goodsId: item.Id,
                            num: item.Num ? item.Num : 1,
                            goodsSSpecId: item.GoodsSpecDtos[0].Id,
                        }
                        that.data.iteamArr.push(obj)

                        console.log(that.data.CouponId, "优惠券id");
                        this.setData({
                            'filter.orderType': item.type || item.Type,
                            'filter.appointmentTime': "",
                            'filter.deliveryTime': "",
                            'filter.doctorUserId': "",
                            'filter.invitationId': "",
                            'filter.orderDetails': this.data.iteamArr,
                            'filter.userAddressId': this.data.Addres,
                            // 'filter.userCouponId':this.data.CouponId,
                            'filter.remarks': this.data.remark
                        })

                        api.order.newOrder(that.data.filter).then((res) => {
                            console.log(res);
                            if (res.data.ErrCode == 0) {

                            } else {

                            }
                        })
                        console.log(that.data.filter);
                    } else if (this.data.from == 3) { // 库存自提下单
                        obj = {
                            goodsId: item.GoodsId,
                            num: item.Num ? item.Num : 1,
                            goodsSSpecId: item.GoodsSpecId
                        }
                        this.setData({
                            'filter.orderType': item.type || item.Type
                        })
                    } else {

                        obj = {
                            goodsId: item.spec.GoodsId,
                            num: item.count,
                            goodsSSpecId: item.spec.Id,

                        }
                        this.setData({
                            'filter.orderType': item.type || item.Type,
                            'filter.userCouponId': this.data.CouponId
                        })
                        console.log(this.data.filter);
                    }

                    arr.push(obj)

                }

                if (orderInfo[0].spec && orderInfo[0].spec.SeckillPric) {
                    this.setData({
                        filter2: {
                            userAddressId: this.data.addressList[0].Id || '',
                            userCouponId: this.data.chosenCoupon && this.data.chosenCoupon.Id || '',
                            remarks: this.data.remark || '',
                            goodsSeckillId: this.data.filter2.goodsSeckillId || '',
                            num: this.data.filter2.num || 1,
                            goodsSSpecId: this.data.filter2.goodsSSpecId || '',
                            orderType: this.data.filter2.orderType || 0,
                            appointmentTime: "",
                            deliveryTime: "",
                            invitationId: wx.getStorageSync('inviteId') || '',
                            doctorUserId: this.data.docId,
                            shareID: wx.getStorageSync('shareID')
                        },
                    })
                }

            } else {
                console.log('来自购物车')
                obj = {
                    goodsId: item.GoodsId,
                    num: item.Num ? item.Num : 1,
                    goodsSSpecId: item.GoodsSpecId
                }
                console.log(this.data.source);
                if (this.data.source != 'kanjia') {
                    this.setData({
                        'filter.orderType': item.GoodsPageDto.Type
                    })
                }


                arr.push(obj)
                console.log(arr);
            }




        })

        this.setData({
            filter: {
                userAddressId: this.data.addressList[0].Id || '',
                userCouponId: this.data.CouponId,
                remarks: this.data.remark || '',
                orderDetails: arr,
                orderType: this.data.filter.orderType || 0,
                appointmentTime: "",
                deliveryTime: "",
                invitationId: wx.getStorageSync('inviteId') || '',
                doctorUserId: this.data.docId,
                shareID: wx.getStorageSync('shareID')
            },

            loading: true
        })

        if (this.data.source === 'zaohui') {
            try {
                // 早惠商品
                let res = await api.activity.orderActivity({
                    id: this.data.activityId,
                    num: this.data.orderInfo[0].count,
                    spec_id: this.data.orderInfo[0].spec.Id,
                    address_id: this.data.addressList[0].Id,
                    remark: this.data.remark
                })

                if (res.data.ErrCode != 0) {
                    this.setData({
                        toast: {
                            visible: true,
                            text: res.data.ErrMsg,
                            loading: false
                        }
                    })
                    return


                } else {
                    this.toPay(res, () => {
                        wx.redirectTo({
                            url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter3.goodsId}`, //&sum=${this.data.sum}&couponcut=${this.data.couponCut}
                        })
                    })
                }

            } catch (e) {
                console.log(e, '拼团下单失败')
                this.setData({
                    toast: {
                        visible: true,
                        text: e.data.ErrMsg,
                    },
                    loading: false
                })
            }
        } else if (this.data.source == 'pingtuan') {
            // 拼团下单
            try {
                let res;

                if (this.data.showBuyData && this.data.showBuyData.isJson && this.data.showBuyData.orderId) {
                    // 参加别人的团
                    res = await api.collage.joinCollage({
                        id: this.data.showBuyData.orderId,
                        num: this.data.orderInfo[0].count,
                        spec_id: this.data.orderInfo[0].spec.Id,
                        address_id: this.data.addressList[0].Id,
                        remark: this.data.remark
                    })
                } else {
                    // 自己开团
                    res = await api.collage.openCollage({
                        collageId: this.data.activityId,
                        num: this.data.orderInfo[0].count,
                        spec_id: this.data.orderInfo[0].spec.Id,
                        address_id: this.data.addressList[0].Id,
                        remark: this.data.remark
                    })
                }
                if (res.data.ErrCode == 0) {
                    this.toPay(res, () => {
                        wx.redirectTo({
                            url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter3.goodsId}`, //&sum=${this.data.sum}&couponcut=${this.data.couponCut}
                        })
                    })
                } else {
                    this.setData({
                        toast: {
                            visible: true,
                            text: res.data.ErrMsg,
                        },
                        loading: false
                    })
                }

                console.log(res, '提交订单', this.data.filter3, 'filter3')
            } catch (e) {
                console.log(e, '拼团下单失败')
                this.setData({
                    toast: {
                        visible: true,
                        text: e.data.ErrMsg,
                    },
                    loading: false
                })
            }
        } else if (this.data.source === 'miaosha') {
            // 秒杀商品提交订单
            try {
                // this.data.filter2
                let res = await api.order.newSeckillOrder({
                    kill_id: this.data.activityId,
                    spec_id: this.data.filter2.goodsSSpecId,
                    num: this.data.filter2.num,
                    address_id: this.data.filter3.userAddressId,
                    remark: this.data.filter3.remarks,
                    address_id: this.data.Addres
                })
                this.toPay(res, () => {
                    wx.redirectTo({
                        url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter2.goodsSeckillId}&sum=${this.data.sum}&couponcut=${this.data.couponCut}`,
                    })
                })
            } catch (e) {
                this.setData({
                    loading: false,
                    toast: {
                        visible: true,
                        text: e.data && e.data.ErrMsg
                    },
                })
            }
        } else if (this.data.source === 'kanjia') {
            console.log(this.data.sum, "砍价总金额");

            let obj = {
                id: Number(that.data.iteams.bargain_id),
                bargain_id: Number(that.data.iteams.id),
                address_id: that.data.Addres,
                spec_id: that.data.iteams.spec_id,
                remark: that.data.remark
            }
            this.reload()
            http.request("POST", "/bargain/bargain_order", obj).then((res) => {
                console.log(res);
                // 砍价0元购
                if (this.data.sum == 0) {
                    let objs = {
                        orderNo: res.data.ResData.orderNo
                    }
                    http.request("POST", "/Pay/bargain_amount_zero", objs).then((res) => {
                        console.log(res);
                        if (res.data.ErrCode == 0) {
                            wx.redirectTo({
                                url: `/pages/product/paySuccess/paySuccess`,
                            })
                        }

                        that.setData({
                            loading: false
                        })
                    })
                } else {
                    that.toPay(res, () => {
                        console.log(res);
                        wx.redirectTo({
                            url: `/pages/product/paySuccess/paySuccess`,
                        })
                    })
                }
            })

        } else {
            // 普通商品提交订单
            try {
                let res = {};
                if (this.data.from == 1 || this.data.from == 0) {

                    res = await api.order.newOrder(this.data.filter);
                } else if (this.data.from == 2) {
                    res = await api.order.replenishment(this.data.filter);
                } else if (this.data.from == 3) {
                    res = await api.order.selfOrder(this.data.filter);
                }

                let paymentId = res.data && res.data.ResData || '';
                console.log(this.data.filter, 'filter参数1')
                if (paymentId) {
                    try {
                        if (this.data.from == 3) {
                            console.log(paymentId);
                            let obj = {
                                order_id: paymentId
                            }
                            http.request('GET', '/AgentWarehouse/SelfWithdrawal', obj).then((res) => {
                                console.log(res);
                                if (res.data.ErrCode != 0) {
                                    console.error(res.data.ErrMsg);
                                    that.setData({
                                        toast: {
                                            visible: true,
                                            text: res.data.ErrMsg
                                        }
                                    })
                                    return
                                } else {
                                    console.log("支付成功");
                                    wx.redirectTo({
                                        url: `/pages/product/paySuccess/paySuccess?type=1`,
                                    })
                                }
                            })
                        } else {
                            let res = await pay.orderPay(paymentId);
                            wx.redirectTo({
                                url: `/pages/product/paySuccess/paySuccess?id=${this.data.filter.orderDetails[0].goodsId}&sum=${this.data.sum}&couponcut=${this.data.couponCut}`,
                            })
                        }
                        this.setData({
                            loading: false
                        })
                        console.log(this.data.filter, 'filter参数2')

                    } catch (e) {
                        console.log(e, '取消订单')
                        if (e.errMsg == 'requestPayment:fail cancel') {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付取消',
                                    loading: false
                                },

                            })
                        } else {
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '支付失败',
                                    loading: false
                                },

                            })
                        }
                        return
                    }



                } else {
                    this.setData({
                        toast: {
                            visible: true,
                            text: res.data.ErrMsg || '支付失败，请重试'
                        }
                    })
                    return
                }

                console.log(res, '提交订单', this.data.filter, 'filter')
            } catch (e) {
                this.setData({
                    loading: false,
                    toast: {
                        visible: true,
                        text: e.data && e.data.ErrMsg,
                        loading: false
                    }
                })
                console.log(e, '提交订单失败')
            }
        }


    },

    /**
     * 调用支付
     * @param {*} res 
     */
    async toPay(res, paySuccess) {
        console.log(res, paySuccess, "45454545");
        let that = this
        console.log('返回信息', res)
        if (res) {
            that.setData({
                loading: false
            })
        }
        let paymentId = res.data.ResData || '';
        let arr = []
        if (typeof (paymentId) == "object") {
            for (var i in paymentId) {
                arr.push(paymentId[i]);
                paymentId = arr[0]
            }
        }

        // console.log('paymentId', arr)
        if (paymentId) {

            try {
                await pay.orderPay(paymentId);

                if (paySuccess && typeof paySuccess == 'function') paySuccess()
            } catch (e) {
                console.log('订单支付失败', e)
                if (e.errMsg == 'requestPayment:fail cancel') {
                    this.setData({
                        toast: {
                            visible: true,
                            text: '支付取消'
                        },
                        loading: false
                    })
                } else {
                    this.setData({
                        toast: {
                            visible: true,
                            text: '支付失败'
                        },
                        loading: false
                    })
                }
            }



            this.setData({
                loading: false
            })
        } else {
            this.setData({
                toast: {
                    visible: true,
                    text: res.data.ErrMsg || '创建订单失败'
                }
            })
            return
        }
    },

    // 计算总价
    getSum() {
        let that = this
        let sum = 0;
        let chooseArr = this.data.orderInfo;
        chooseArr.forEach(item => {

            if (this.data.from == 1) {
                if (this.data.orderTypes != "goods") {
                    if (this.data.orderTypes == "pingtuan" || this.data.orderTypes == "zaohui") {
                        sum += item.spec.Price * item.count
                        console.log("拼团产品的价格", sum);
                    } else {
                        sum += item.spec.SeckillPric * item.count
                        console.log("活动产品的价格", sum);
                    }

                } else {
                    sum += item.spec.price * item.count
                    console.log("普通产品的价格", sum);
                }
                console.log(sum)

                // this.setData({
                //     sums: sum
                // })
                // let {
                //     Id
                // } = wx.getStorageSync('userinfo')
                // console.log(Id);
                // let obj = {
                //     user_id: Id,
                //     money: sum
                // }
                // http.request("POST", "/Order/PayAmount", obj).then((res) => {
                //     if (res.data.ErrCode == 0) {
                //         that.setData({
                //             sum: res.data.ResData.money,
                //             iteamSum:res.data.ResData.money,
                //             sumText: res.data.ResData.remake
                //         })
                //     } else {
                //         console.error(res.data.ErrMsg);
                //     }
                // })
            } else if (this.data.from == 0) {
                console.log(that.data.orderTypes, 9999999);

                if (that.data.orderTypes == 'kanjia') {
                    sum += item.spec.price * item.count
                    console.log("砍价产品的价格", sum);
                } else {
                    sum += (item.Amount) * Number(item.Num ? item.Num : 1)
                    console.log("普通产品的价格", sum);
                }
                console.log(sum)

                // that.setData({
                //     sums: sum
                // })
                // let {
                //     Id
                // } = wx.getStorageSync('userinfo')
                // console.log(Id);
                // let obj = {
                //     user_id: Id,
                //     money: sum
                // }
                // http.request("POST", "/Order/PayAmount", obj).then((res) => {
                //     console.log(res);
                //     if (res.data.ErrCode == 0) {
                //         that.setData({
                //             sum: res.data.ResData.money,
                //             iteamSum:res.data.ResData.money,
                //             sumText: res.data.ResData.remake
                //         })
                //         console.log(res.data.ResData);
                //     } else {
                //         console.error(res.data.ErrMsg);
                //     }
                // })
            } else if (this.data.from == 2) {
                sum += Number(item.Price) * Number(item.Num ? item.Num : 1)
                console.log(sum);
                // that.setData({
                //     sums: sum
                // })
                // let {
                //     Id
                // } = wx.getStorageSync('userinfo')
                // console.log(Id);
                // let obj = {
                //     user_id: Id,
                //     money: sum
                // }
                // http.request("POST", "/Order/PayAmount", obj).then((res) => {
                //     console.log(res);
                //     if (res.data.ErrCode == 0) {
                //         that.setData({
                //             sum: res.data.ResData.money,
                //             iteamSum:res.data.ResData.money,
                //             sumText: res.data.ResData.remake
                //         })
                //         console.log(res.data.ResData);
                //     } else {
                //         console.error(res.data.ErrMsg);
                //     }
                // })
            } else if (this.data.from == 3) {
                console.log(item, 'mmp', item.GoodsDto.Price, item.Num, (item.GoodsDto.Price) * Number(item.Num))
                sum += (item.GoodsDto.Price) * Number(item.Num ? item.Num : 1)
                console.log(sum)
            }

        })
        that.setData({
            sums: sum
        })
        let {
            Id
        } = wx.getStorageSync('userinfo')
        console.log(Id);
        let obj = {
            user_id: Id,
            money: sum
        }
        http.request("POST", "/Order/PayAmount", obj).then((res) => {
            console.log(res);
            if (res.data.ErrCode == 0) {
                that.setData({
                    sum: res.data.ResData.money,
                    iteamSum: res.data.ResData.money,
                    sumText: res.data.ResData.remake
                })
                console.log(res.data.ResData);
            } else {
                console.error(res.data.ErrMsg);
            }
        })

        // let discount = 0;
        // let disList = this.data.discountList || [];
        // console.log('折扣計算')
        // console.log('dislits', disList[0].GreenPrice, '11', disList[1].GreenPrice, '22')

        // if (disList.length && !this.data.agentInfo.MemberGradeId) {
        //     if (sum >= disList[0].GreenPrice && sum < disList[1].GreenPrice) {
        //         discount = sum * (disList[0].GreenDiscount / 100);
        //     } else if (sum >= disList[1].GreenPrice) {
        //         discount = sum * (disList[1].GreenDiscount / 100);
        //     }
        // }

        sum = sum + that.data.ShippingAmount
        this.setData({
            sum: sum.toFixed(1),
            discount: discount.toFixed(1)
        })
    },

    // 折扣信息
    async getDiscount() {
        try {
            let res = await api.order.getDiscount(),
                data = res.data.ResData || [];

            let discountList = data.splice(0, 2);
            console.log(res, '折扣信息')
            this.setData({
                discountList
            })
            if (this.data.iteams?.isCar != 1) {
                this.getSum()
            }
        } catch (e) {
            console.log(e, '折扣失败')
        }
    }
})